package im.composer.audioservers.dummy;

import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.jaudiolibs.audioservers.AudioClient;
import org.jaudiolibs.audioservers.AudioConfiguration;
import org.jaudiolibs.audioservers.AudioServer;

/**
 * DummyAudioServer , which comes with no actual audio input and output.
 * 
 * @author david
 * 
 */
public class DummyAudioServer implements AudioServer {

	protected final AudioConfiguration audioContext;
	protected final AudioClient client;
	protected boolean active = false;

	public DummyAudioServer(AudioClient client, AudioConfiguration audioContext) {
		super();
		this.client = client;
		this.audioContext = audioContext;
	}

	@Override
	public void run() throws Exception {
		long frame_time_nano = (long) (audioContext.getMaxBufferSize() / audioContext.getSampleRate() * Math.pow(10, 9));
		client.configure(audioContext);
		active = true;
		while (isActive()) {
			client.process(System.nanoTime(), prepareBuffer(audioContext.getInputChannelCount()), prepareBuffer(audioContext.getOutputChannelCount()), audioContext.getMaxBufferSize());
			TimeUnit.NANOSECONDS.sleep(frame_time_nano);
		}
	}

	protected List<FloatBuffer> prepareBuffer(int count) {
		List<FloatBuffer> list = new ArrayList<>(count);
		for (int i = 0; i < count; i++) {
			list.add(FloatBuffer.wrap(new float[audioContext.getMaxBufferSize()]));
		}
		return Collections.unmodifiableList(list);
	}

	@Override
	public AudioConfiguration getAudioContext() {
		return audioContext;
	}

	@Override
	public boolean isActive() {
		return active;
	}

	@Override
	public void shutdown() {
		active = false;
	}

}
